import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken, getLoginType, setLoginType, removeLoginType, getEnterpriseType, setEnterpriseType, removeEnterpriseType } from '@/utils/auth'
import { resetRouter } from '@/router'
// import { MessageBox } from 'element-ui'
// 获取当前登录人的信息
import { getIndexInfo, getAccountInfo } from '@/api/system/sys-index'

import { constantRoutes } from '@/router'
import Layout from '@/layout/index'

const state = {
  token: getToken(),
  name: 'admin',
  avatar: '',
  introduction: '',
  menu: [],
  // 左侧导航栏
  leftMenu: [],
  // 兼职部门id
  partId: '',
  // 操作权限
  permissions: [],
  // 到期时间
  day: '',
  // 联系电话
  phone: '',
  // 即将到期的企业
  enterpriseExpiryTime: [],
  // 当前登录人用户信息
  userInfo: '',
  // 用户类型
  userType: '',
  // 账号类型
  loginType: getLoginType(),
  // 企业类型
  enterpriseType: getEnterpriseType(),
  // 用户信息(主界面)
  sysAccount: '',
  // 版权年份
  copyrightYear: '',
  // 证书过期列表
  certificateDate: [],
  // 证书过期天数
  certificateExpire: '',
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
  },
  SET_LEFT_MENU: (state, leftMenu) => {
    state.leftMenu = leftMenu
  },
  SET_PQRTID: (state, partId) => {
    state.partId = partId
  },
  // 按钮操作权限
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  // 到期时间
  SET_DAY: (state, day) => {
    state.day = day
  },
  // 联系电话
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  // admin可以查看的即将到期的企业
  SET_ENTERPRISEEXPRIRYTIME: (state, enterpriseExpiryTime) => {
    state.enterpriseExpiryTime = enterpriseExpiryTime
  },
  // 当前登录人员工信息
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  // 当前登录人用户类型
  SET_USER_TYPE: (state, userType) => {
    state.userType = userType
  },
  // 当前登录人账号类型
  SET_LOGIN_TYPE: (state, loginType) => {
    state.loginType = loginType
  },
  // 设置登录的企业类型
  SET_ENTERPRISE_TYPE: (state, enterpriseType) => {
    state.enterpriseType = enterpriseType
  },
  // 用户信息
  SET_SYS_ACCOUNT: (state, sysAccount) => {
    state.sysAccount = sysAccount
  },
  // 获取年份
  SET_COPYRIGHTYEAR: (state, copyrightYear) => {
    state.copyrightYear = copyrightYear
  },
  // 证书过期列表
  SET_CERTIFICATE_DATE: (state, certificateDate) => {
    state.certificateDate = certificateDate
  },
  // 证书过期天数
  SET_CERTIFICATEEXPIRE: (state, certificateExpire) => {
    state.certificateExpire = certificateExpire
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // 用户左侧导航栏
  setLeftMenu({ commit }, leftMenu) {
    commit('SET_LEFT_MENU', leftMenu)
  },
  // 登录
  login({ commit }, userInfo) {
    const { username, password, rememberMe, code, uuid } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, rememberMe: rememberMe, code: code, uuid: uuid }).then(res => {
        const data = res.data
        setToken(data.access_token)
        commit('SET_LOGIN_TYPE', data.login_type)
        commit('SET_TOKEN', data.access_token)
        setLoginType(data.login_type)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 扫码登录省去获取token步骤
  scanCodeLogin({ commit }, data) {
    return new Promise(resolve => {
      setToken(data.access_token)
      commit('SET_LOGIN_TYPE', data.login_type)
      commit('SET_TOKEN', data.access_token)
      setLoginType(data.login_type)
      resolve(data)
    })
  },
  // 获取用户信息
  getInfo({ dispatch, commit, state }) {
    return new Promise((resolve, reject) => {
      // 兼职部门id
      let partId = state.partId
      if (partId === 0) { // partId :0 的时候 是原部门
        partId = ''
      }
      getIndexInfo(partId).then(response => {
        const { data } = response
        if (!data) {
          reject('验证失效，请重新登录')
        }
        // const { roles, introduction, loginType, menu, permissions, sysAccount, user, user: { appFiles }, day, phone, enterpriseExpiryTime } = data
        const { user: { avatar }, roles, introduction, certificateExpire, enterpriseType, menu, permissions, userCertificate, enterpriseCertificate, sysAccount, user, day, phone, enterpriseExpiryTime } = data
        if (menu != null) {
          if (user.userType === '00' || user.userType === '05') {
            commit('SET_CERTIFICATE_DATE', userCertificate)
          } else if (user.userType === '01' || user.userType === '03') {
            commit('SET_CERTIFICATE_DATE', enterpriseCertificate)
          }
          commit('SET_CERTIFICATEEXPIRE', certificateExpire)
          commit('SET_MENU', menu)
          commit('SET_ROLES', roles)
          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)
          commit('SET_PERMISSIONS', permissions)
          commit('SET_DAY', day)
          commit('SET_PHONE', phone)
          commit('SET_ENTERPRISEEXPRIRYTIME', enterpriseExpiryTime)
          // 当前登录人用户信息
          commit('SET_USER_INFO', user)
          commit('SET_USER_TYPE', user.userType)
          // commit('SET_LOGIN_TYPE', loginType)
          commit('SET_ENTERPRISE_TYPE', enterpriseType)
          setEnterpriseType(enterpriseType)
          commit('SET_SYS_ACCOUNT', sysAccount)
          // localStorage.setItem('menuUrl', JSON.stringify(menuUrl))
          const accessedRoutes = filterAsyncRouter(menu)
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }
        // else {
        //   if (user.userType !== '') {
        //     location.href = '/user-profile/profile'
        //   }
        // }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then((res) => {
        if (res) {
          commit('SET_USER_INFO', '')
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_MENU', [])
          commit('SET_MENU', [])
          commit('SET_LEFT_MENU', [])
          commit('SET_PQRTID', '')
          removeToken()
          resetRouter()
          removeLoginType()
          removeEnterpriseType()
          dispatch('tagsView/delAllViews', null, { root: true })
          location.href = '/main'
          resolve()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 删除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
  // 用户主页面接口
  getAccountInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getAccountInfo().then(res => {
        const { sysUserAccount: sysAccount, introduction, roles, copyrightYear } = res.data
        commit('SET_ROLES', roles)
        commit('SET_NAME', sysAccount.name)
        commit('SET_AVATAR', sysAccount.avatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_COPYRIGHTYEAR', copyrightYear)
        // 当前登录人用户信息
        commit('SET_SYS_ACCOUNT', sysAccount)
        resolve()
      })
    })
  }

}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
